<template>
  <el-card
    :body-style="{ padding: '20px' }"
    :style="`height:${windowHeight}px;`"
  >
    <el-row>
      <el-col
        :span="24"
        style="
          text-align: center;
          padding: 20px;
          font-weight: 600;
          font-size: 16px;
        "
        >批量MPDI计算(自动处理)</el-col
      >
    </el-row>

    <!-- 中间部分 -->
    <div class="content-card">
      <el-card :body-style="{ padding: '20px' }" class="card">
        <h3 style="margin-bottom: 20px">文件选择</h3>
        <el-row :gutter="20">
          <!-- 选择盘符 -->

          <el-col
            :span="4"
            style="display: flex; align-items: center; margin-bottom: 20px"
          >
            <span>选择盘符</span>&nbsp;&nbsp;
            <el-select
              v-model="selectedDrive"
              placeholder="选择盘符"
              style="width: 200px"
              filterable
              @change="loadDirectoryTree"
              size="small"
            >
              <el-option
                v-for="drive in driveOptions"
                :key="drive"
                :label="drive"
                :value="drive"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!-- 左侧目录树 -->
          <el-col :span="6">
            <el-card class="tree-card">
              <h4 style="margin-bottom: 20px">目录列表</h4>
              <el-tree
                :data="directoryTree"
                :props="treeProps"
                node-key="fullPath"
                :highlight-current="true"
                @node-click="loadFiles"
                lazy
                :load="loadChildren"
                :style="`height:${windowHeight - 400}px; overflow:auto;`"
              />
            </el-card>
          </el-col>
          <!-- 右侧文件列表 -->
          <el-col :span="18">
            <el-card class="file-card">
              <el-row style="margin-bottom: 10px">
                <el-col
                  :span="24"
                  style="display: flex; justify-content: space-between"
                >
                  <h4 style="margin-bottom: 20px">文件列表</h4>
                  <el-button type="primary" @click="showConfirmationDialog">
                    MPDI计算
                  </el-button>
                </el-col></el-row
              >
              <el-table
                :data="files"
                style="width: 100%"
                @selection-change="handleSelectionChange"
                highlight-current-row
                :border="true"
                :style="`height:${windowHeight - 400}px; overflow:auto`"
              >
                <el-table-column
                  type="selection"
                  width="55"
                  :align="'center'"
                />
                <el-table-column prop="name" label="文件名" />
                <el-table-column prop="size" label="文件大小" width="150" />
                <el-table-column
                  prop="extension"
                  label="扩展名"
                  width="100"
                  :filters="extensionFilters"
                  :filter-method="filterExtension"
                  filter-placement="bottom"
                ></el-table-column>
                <el-table-column
                  prop="created"
                  label="创建时间"
                  :align="'center'"
                  width="250"
                />
                <el-table-column
                  prop="lastModified"
                  label="最后修改时间"
                  :align="'center'"
                  width="250"
                />
                <el-table-column prop="isReadOnly" label="只读" width="100" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </el-card>

  <!-- 文件移植确认弹窗 -->
  <el-dialog
    title="确认移植文件"
    v-model="confirmationDialogVisible"
    width="800px"
    @close="dialogCloseHandler"
  >
    <el-row :gutter="20" style="margin-bottom: 20px">
      <!-- 灌区位置 -->
      <el-col :span="12" style="display: flex">
        <span>所属灌区&nbsp;&nbsp;</span>
        <el-select
          v-model="irrigationArea"
          placeholder="选择灌区"
          style="width: calc(100% - 70px)"
          @change="clacPath"
          size="small"
        >
        <el-option label="河套灌区" value="河套灌区"></el-option>
        <el-option label="石津灌区" value="石津灌区"></el-option>
        </el-select>
      </el-col>
      <!-- 日期选择 -->
      <el-col :span="12" style="display: flex">
        <span>生产时间&nbsp;&nbsp;</span>
        <el-date-picker
          v-model="dateTime"
          type="datetime"
          placeholder="选择日期"
          style="width: calc(100% - 70px)"
          size="small"
          @change="clacPath"
        ></el-date-picker>
      </el-col>
    </el-row>

    <el-row style="margin-bottom: 20px">
      <el-col :span="24">
        <span style="margin-bottom: 10px">生产目标路径&nbsp;&nbsp;</span>
        <el-input
          v-model="generatedVirtualPath"
          style="width: calc(100% - 100px)"
        />
      </el-col>
    </el-row>
    <el-card>
      <el-row>
        <el-col :span="24" style="margin-bottom: 10px"
          ><span>已选文件</span>
        </el-col>
      </el-row>
      <el-table
        :data="selectedFiles"
        style="width: 100%"
        :style="`height:${windowHeight - 500}px`"
        :border="true"
      >
        <el-table-column prop="name" label="文件名" />
        <el-table-column prop="size" label="文件大小" width="150" />
        <el-table-column prop="lastModified" label="最后修改时间" width="250" />
      </el-table>
    </el-card>
    <el-row>
      <el-col style="text-align: center; padding: 20px 0 0">
        <el-button type="primary" @click="moveFiles">确认</el-button>
        <el-button @click="confirmationDialogVisible = false">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>

  <!-- 进度弹窗 -->
  <el-dialog title="文件移植进度" v-model="progressDialogVisible" width="500px">
    <el-progress :percentage="progress" />
    <span>{{ progress }}%</span>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import utils from "@/utils/util";
import { useRouter } from "vue-router";

// 数据模型
const driveOptions = ref<string[]>(["C:", "D:", "E:", "F:", "G:"]);
const directoryTree = ref([]);
const files = ref<any[]>([]);
const selectedFiles = ref([]);
const selectedDrive = ref<string>("D:");
const irrigationArea = ref<string>("河套灌区");
const formattedDate = ref("");
const dateTime = ref(new Date());
const targetPath = ref<string>("");
const generatedVirtualPath = ref<string>(
  `D:/16_MPDI生产/${irrigationArea.value}/${formattedDate.value}/01_正射影像`
);
const router = useRouter();
// 弹窗数据
const confirmationDialogVisible = ref(false);
const progressDialogVisible = ref(false);
const progress = ref(0);

// 保存窗口高度
const windowHeight = ref(window.innerHeight);

// 树结构配置
const treeProps = { children: "children", label: "label", isLeaf: "leaf" };
const handleSelectionChange = (val) => {
  selectedFiles.value = val;
};

// 加载目录树
const loadDirectoryTree = async () => {
  if (selectedDrive.value) {
    try {
      const response = await axios.get("/algorithmApi/cutApi/directoryTree", {
        params: { path: selectedDrive.value },
      });
      directoryTree.value = response.data.directoryTree;
    } catch (error) {
      ElMessage.error("加载目录树失败");
    }
  }
};

// 加载子目录
const loadChildren = async (node: any, resolve: Function) => {
  if (node.data.fullPath) {
    try {
      const response = await axios.get("/algorithmApi/cutApi/directoryTree", {
        params: { path: node.data.fullPath },
      });
      node.children = response.data.directoryTree;
      resolve(node.children); // 必须调用 resolve 来通知加载完成
    } catch (error) {}
  }
};

// 获取文件列表
const loadFiles = async (node) => {
  try {
    const response = await axios.get("/algorithmApi/cutApi/files", {
      params: { path: node.fullPath },
    });
    files.value = response.data.files.map((file: any) => {
      return {
        name: file.name,
        size: formatSize(file.size), // 文件大小
        lastModified: utils.formatDate(file.lastModified), // 最后修改时间
        extension: file.extension, // 文件扩展名
        created: utils.formatDate(file.created), // 文件创建时间
        path: file.path, // 文件完整路径
        isReadOnly: file.isReadOnly ? "是" : "否", // 判断文件是否为只读
        permissions: file.permissions, // 文件权限
      };
    });

    // 更新扩展名筛选器
    extensionFilters.value = getUniqueExtensions().map((ext) => ({
      text: ext.toUpperCase(),
      value: ext,
    }));
  } catch (error) {
    ElMessage.error("加载文件列表失败");
  }
};

// 格式化文件大小
function formatSize(sizeInBytes: number): string {
  const units = ["B", "KB", "MB", "GB", "TB"];
  let size = sizeInBytes; // 初始单位为B（字节）

  let i = 0;
  while (size >= 1024 && i < units.length - 1) {
    size /= 1024;
    i++;
  }

  return `${size.toFixed(2)} ${units[i]}`;
}

// 获取文件扩展名并去重
const getUniqueExtensions = () => {
  const extensions = files.value.map((file) => file.extension);
  const uniqueExtensions = [...new Set(extensions)];
  return uniqueExtensions;
};

// 扩展名筛选方法
const filterExtension = (value, row) => {
  return row.extension.toLowerCase() === value.toLowerCase();
};

const extensionFilters = ref([]);

// 显示确认弹窗
const showConfirmationDialog = () => {
  if (selectedFiles.value.length == 0) {
    ElMessage.warning("请先选择要处理的文件");
    return;
  }
  clacPath();
  confirmationDialogVisible.value = true;
};

const clacPath = function () {
  const date = new Date(dateTime.value);
  const CST_OFFSET = 8 * 60 * 60 * 1000;
  const cstDate = new Date(date.getTime() + CST_OFFSET);

  const year = cstDate.getFullYear();
  const month = String(cstDate.getMonth() + 1).padStart(2, "0");
  const day = String(cstDate.getDate()).padStart(2, "0");
  const hours = String(cstDate.getHours()).padStart(2, "0");
  const minutes = String(cstDate.getMinutes()).padStart(2, "0");
  const seconds = String(cstDate.getSeconds()).padStart(2, "0");
  formattedDate.value = `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;
  generatedVirtualPath.value = `D:/16_MPDI生产/${irrigationArea.value}/${formattedDate.value}/01_正射影像`;
};

const dialogCloseHandler = function () {
  confirmationDialogVisible.value = false;
};
// 文件移植
const moveFiles = async () => {
  progressDialogVisible.value = true;
  try {
    await axios.post("/algorithmApi/cutApi/move", {
      files: selectedFiles.value,
      targetPath: generatedVirtualPath.value,
    });
    progress.value = 100;
    ElMessage.success("批量MPDI计算自动任务已提交");
    // window.open("/index/general/executeManage/executeList");
    router.push("/index/general/executeManage/executeList")
    progressDialogVisible.value = false;
  } catch (error) {
    ElMessage.error("批量MPDI计算自动任务提交失败");
    progressDialogVisible.value = false;
  }
};

loadDirectoryTree();
</script>

<style scoped lang="scss">
.container {
  padding: 20px;
}
</style>
